<template>
  <div class="container-wrapper">
    <div class="container">
      <img class="container-bg" :src="require('../assets/image/bg2.png')">
      <div class="school-bg" :style="`backgroundImage: url('${randomBg}')`">
      </div>
      <div class="modal">
        <div class="text-view">
          <div class="title">{{randomSchoolName}} <span class="profession-name">{{randomProfessionName}}</span></div>
          <div class="desc">{{randomProfessionDesc}}</div>
        </div>
      </div>
      <img class="person" :src="result[activeIndex]">
      <div class="tabs">
        <img @click="handleSwich(index)" :src="tabImages[index]" :class="['tab', 'tab' + (+index + 1), { hidden: activeIndex != index }]" v-for="(item, index) in tabImages" :key="index">
      </div>
      <img class="loading" v-show="loading" :src="require('../assets/image/loading.png')">
      <!-- <div class="retry" @click="handleRetry"></div> -->
      <div class="share" @click="handleShare"></div>
      <t-dialog v-show="visible" enter-text="返回选择" @enter="handleEnter">{{dialogText}}</t-dialog>
      <canvas ref="canvas" v-show="false"></canvas>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import { zipImage } from '../utils/common.js'

export default {
  name: 'confirm',
  computed: {
    ...mapGetters([
      'result', 'randomBg', 'randomProfessionName', 'randomProfessionDesc', 'randomSchoolName'
    ]),
    loading () {
      return this.loadingIndex.indexOf(this.activeIndex) !== -1
    }
  },
  components: {
    't-dialog': require('../components/Dialog.vue').default
  },
  data () {
    return {
      tabImages: [
        require('../assets/tabs/1.png'),
        require('../assets/tabs/2.png'),
        require('../assets/tabs/3.png'),
        require('../assets/tabs/4.png'),
        require('../assets/tabs/5.png')
      ],
      // loading: false,
      loadingIndex: [],
      activeIndex: 0,
      dialogText: '',
      visible: false
    }
  },
  methods: {
    ...mapActions(['getMergedFace']),
    handleEnter () {
      this.$router.replace('/home')
    },
    handleSwich (index) {
      this.activeIndex = index
      if (this.loading || this.result[index]) return
      this.loadingIndex.push(index)
      this.getMergedFace(index).then(() => {
        const lindex = this.loadingIndex.indexOf(index)
        this.loadingIndex.splice(lindex, 1)
      }).catch(error => {
        if (error === '2001' || error === '2002' || (error + '').charAt(0) === '5' || isNaN(+error)) {
          window._hmt.push(['_trackEvent', '结果页', 'dialog', '出现服务器故障提示'])
          this.dialogText = '小猿出现故障惹，等会儿嗷'
        } else if (error === '1002') {
          window._hmt.push(['_trackEvent', '结果页', 'dialog', '出现非人脸弹窗提示'])
          this.dialogText = '找不到脸部，重新挑选一张照片吧!'
        } else {
          window._hmt.push(['_trackEvent', '结果页', 'dialog', '出现网络罢工提示'])
          this.dialogText = '天啦噜，你的网络罢工了，请检查网络'
        }
        this.visible = true
        this.loading = false
      })
    },
    handleRetry () {
      window._hmt.push(['_trackEvent', '结果页', 'click', '点击再测一次'])
      this.$router.replace('/home')
    },
    handleShare () {
      window._hmt.push(['_trackEvent', '结果页', 'click', '点击炫耀一下/立即分享'])
      this.shareReady(true)
        .then(shareImage => {
          console.log(shareImage)
        })
    },
    // 文字根据宽度换行
    drawText (context, t, x, y, w) {
      const chr = t.split('')
      let temp = ''
      const row = []
      for (let a = 0; a < chr.length; a++) {
        if (context.measureText(temp).width >= w) {
          row.push(temp)
          temp = ''
        }
        temp += chr[a]
      }
      row.push(temp)
      for (let b = 0; b < row.length; b++) {
        context.fillText(row[b], x, y + (b + 1) * 40)
      }
    },
    // 开始作图
    draw ({ bg, qrcode, randomBg, person }) {
      const canvas = this.$refs.canvas
      // 初始化canvas
      canvas.width = 750
      canvas.height = 1400
      const context = canvas.getContext('2d')
      // 主体背景绘制
      context.drawImage(bg, 0, 0, 750, 1400)
      // 学校背景绘制
      context.drawImage(randomBg, 27, 26, 696, 960)
      // 二维码绘制
      context.drawImage(qrcode, 580, 1176, 144, 144)
      // 绘制人物
      context.drawImage(person, 470, 620, 240, 540)
      // 绘制文字标题
      context.font = '400 40px 微软雅黑'
      context.fillStyle = '#ffffff'
      context.fillText(this.randomSchoolName, 40, 1045, 2000)
      const schoolNameWidth = context.measureText(this.randomSchoolName)
      context.font = '400 36px 微软雅黑'
      context.fillStyle = '#ffffff'
      context.fillText(this.randomProfessionName, schoolNameWidth.width + 60, 1045, 2000)
      context.font = '200 28px 微软雅黑'
      // 绘制文字内容
      this.drawText(context, this.randomProfessionDesc, 50, 1055, 470)
      return this.$refs.canvas.toDataURL('image/png')
    },
    shareReady (shouldExport) {
      const bg = new Image()
      bg.src = require('../assets/image/share.png')
      const qrcode = new Image()
      qrcode.src = require('../assets/image/qrcode.png')
      const personImage = this.result[this.activeIndex]
      if (!personImage) return
      const person = new Image()
      person.src = personImage
      const randomBg = new Image()
      randomBg.src = this.randomBg
      // 等待四张图片都加载好后开始作图
      if (!shouldExport) return
      return Promise.all([bg, qrcode, person, randomBg].map(i => new Promise(resolve => { i.onload = resolve }))).then(
        () => {
          return zipImage(this.draw({ bg, qrcode, person, randomBg }))
        }).catch(() => {
        window._hmt.push(['_trackEvent', '结果页', 'dialog', '出现网络罢工提示'])
        this.dialogText = '天啦噜，你的网络罢工了，请检查网络'
        this.visible = true
      })
    }
  },
  created () {
    if (!this.result[0]) {
      this.$router.replace('/home')
    } else {
      window._hmt.push(['_trackEvent', '结果页', 'view', '进入结果页'])
    }
  },
  mounted () {
    this.shareReady(false)
  }
}
</script>

<style scoped>
.container-wrapper {
  width: 100%;
  height: 100%;
  overflow: scroll;
  display: flex;
  flex-direction: column;
}

.container {
  position: relative;
  width: 100%;
  min-height: 1200px;
  flex: 1;
  background-repeat: no-repeat;
  background-size: 100%;
  overflow: hidden;
}

.container-bg {
  top: 0;
  width: 100%;
}

.tabs {
  position: absolute;
  top: 952px;
  left: 103px;
  height: 72px;
  font-size: 0;
}

.tab {
  height: 100%;
  width: 108px;
}

.tab.hidden {
  opacity: 0;
}

.modal {
  position: absolute;
  top: 686px;
  left: 20px;
  right: 22px;
  height: 262px;
  border-bottom-left-radius: 50px;
  border-bottom-right-radius: 50px;
  background-color: rgba(117, 62, 146, 0.5);
}

.person {
  position: absolute;
  top: 350px;
  left: 450px;
  height: 560px;
}

.school-bg {
  position: absolute;
  top: 60px;
  left: 62px;
  right: 62px;
  height: 850px;
  background-size: 100%;
  border-radius: 20px;
}

.school-bg .loading-modal {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background-color: #444444;
  z-index: 9999;
  opacity: .4;
}

.loading {
  position: absolute;
  width: 50px;
  height: 50px;
  right: 145px;
  top: 600px;
  animation: rotate .8s infinite linear;
  z-index: 10000;
}

.retry {
  position: absolute;
  background-color: #000;
  left: 47px;
  top: 1091px;
  height: 74px;
  width: 316px;
  opacity: 0;
}

.share {
  position: absolute;
  background-color: #000;
  left: 210px;
  top: 1085px;
  height: 85px;
  width: 328px;
  opacity: 0;
}

.modal .text-view {
  margin-left: 40px;
  margin-top: 30px;
  margin-right: 215px;
  z-index: 999;
  font-weight: 200;
}

.modal .text-view .title {
  font-size: 40px;
  line-height: 55px;
  color: #ffffff;
  font-weight: 400;
}

.modal .text-view .title>.profession-name {
  font-size: 36px;
  font-weight: 400;
}

.modal .text-view .desc {
  margin-left: 10px;
  margin-top: 15px;
  font-size: 28px;
  line-height: 40px;
  color: #ffffff;
}

@keyframes rotate {
  to {
    transform: rotate(360deg);
  }
}
</style>
